package ru.electron.menu.network;

import android.os.AsyncTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.DefaultedHttpParams;
import org.json.JSONObject;
import ru.electron.menu.utils.NetUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.concurrent.Callable;

public class PostTask extends AsyncTask<JSONObject, Void, HttpResponse> {


    public void setSuccessAction(SuccessAction successAction) {
        this.successAction = successAction;
    }

    public void setOnFailureAction(Runnable onFailureAction) {
        this.onFailureAction = onFailureAction;
    }

    public interface SuccessAction {
        void onSuccess(HttpResponse response);
    }

    private Runnable onFailureAction;
    private SuccessAction successAction;

    private final String url;

    public PostTask(String partUrl) {
        this.url = NetUtils.getServerUrl() + partUrl;
    }

    @Override
    protected HttpResponse doInBackground(JSONObject... jsonObjects) {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        try {
            String toPost = jsonObjects[0].toString();
            NameValuePair pair = new BasicNameValuePair("request", toPost);
            post.setEntity(new UrlEncodedFormEntity(Collections.singletonList(pair)));

            return client.execute(post);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(HttpResponse response) {
        if (response == null || response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            if (onFailureAction != null) onFailureAction.run();
        } else {
            if (successAction != null) successAction.onSuccess(response);
        }

    }
}
